﻿#region Using directives

using System;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;

using SecurityFoundation.Entities;
using SecurityFoundation.Data;

#endregion

namespace SecurityFoundation.Data.Bases
{	
	///<summary>
	/// This class is the base class for any <see cref="ObjectDefinitionProviderBase"/> implementation.
	/// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures.
	///</summary>
	public abstract partial class ObjectDefinitionProviderBaseCore : EntityProviderBase<SecurityFoundation.Entities.ObjectDefinition, SecurityFoundation.Entities.ObjectDefinitionKey>
	{		
		#region Get from Many To Many Relationship Functions
		#endregion	
		
		#region Delete Methods

		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to delete.</param>
		/// <returns>Returns true if operation suceeded.</returns>
		public override bool Delete(TransactionManager transactionManager, SecurityFoundation.Entities.ObjectDefinitionKey key)
		{
			return Delete(transactionManager, key.ObjectId);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="_objectId">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public bool Delete(System.Guid _objectId)
		{
			return Delete(null, _objectId);
		}
		
		/// <summary>
		/// 	Deletes a row from the DataSource.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_objectId">. Primary Key.</param>
		/// <remarks>Deletes based on primary key(s).</remarks>
		/// <returns>Returns true if operation suceeded.</returns>
		public abstract bool Delete(TransactionManager transactionManager, System.Guid _objectId);		
		
		#endregion Delete Methods
		
		#region Get By Foreign Key Functions
	
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_ObjectDefinition_ApplicationDefination key.
		///		FK_ObjectDefinition_ApplicationDefination Description: 
		/// </summary>
		/// <param name="_applicationKey"></param>
		/// <returns>Returns a typed collection of SecurityFoundation.Entities.ObjectDefinition objects.</returns>
		public TList<ObjectDefinition> GetByApplicationKey(System.Guid _applicationKey)
		{
			int count = -1;
			return GetByApplicationKey(_applicationKey, 0,int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_ObjectDefinition_ApplicationDefination key.
		///		FK_ObjectDefinition_ApplicationDefination Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_applicationKey"></param>
		/// <returns>Returns a typed collection of SecurityFoundation.Entities.ObjectDefinition objects.</returns>
		/// <remarks></remarks>
		public TList<ObjectDefinition> GetByApplicationKey(TransactionManager transactionManager, System.Guid _applicationKey)
		{
			int count = -1;
			return GetByApplicationKey(transactionManager, _applicationKey, 0, int.MaxValue, out count);
		}
		
			/// <summary>
		/// 	Gets rows from the datasource based on the FK_ObjectDefinition_ApplicationDefination key.
		///		FK_ObjectDefinition_ApplicationDefination Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_applicationKey"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		///  <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of SecurityFoundation.Entities.ObjectDefinition objects.</returns>
		public TList<ObjectDefinition> GetByApplicationKey(TransactionManager transactionManager, System.Guid _applicationKey, int start, int pageLength)
		{
			int count = -1;
			return GetByApplicationKey(transactionManager, _applicationKey, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_ObjectDefinition_ApplicationDefination key.
		///		fkObjectDefinitionApplicationDefination Description: 
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_applicationKey"></param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of SecurityFoundation.Entities.ObjectDefinition objects.</returns>
		public TList<ObjectDefinition> GetByApplicationKey(System.Guid _applicationKey, int start, int pageLength)
		{
			int count =  -1;
			return GetByApplicationKey(null, _applicationKey, start, pageLength,out count);	
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_ObjectDefinition_ApplicationDefination key.
		///		fkObjectDefinitionApplicationDefination Description: 
		/// </summary>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="_applicationKey"></param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns a typed collection of SecurityFoundation.Entities.ObjectDefinition objects.</returns>
		public TList<ObjectDefinition> GetByApplicationKey(System.Guid _applicationKey, int start, int pageLength,out int count)
		{
			return GetByApplicationKey(null, _applicationKey, start, pageLength, out count);	
		}
						
		/// <summary>
		/// 	Gets rows from the datasource based on the FK_ObjectDefinition_ApplicationDefination key.
		///		FK_ObjectDefinition_ApplicationDefination Description: 
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_applicationKey"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns a typed collection of SecurityFoundation.Entities.ObjectDefinition objects.</returns>
		public abstract TList<ObjectDefinition> GetByApplicationKey(TransactionManager transactionManager, System.Guid _applicationKey, int start, int pageLength, out int count);
		
		#endregion

		#region Get By Index Functions
		
		/// <summary>
		/// 	Gets a row from the DataSource based on its primary key.
		/// </summary>
		/// <param name="transactionManager">A <see cref="TransactionManager"/> object.</param>
		/// <param name="key">The unique identifier of the row to retrieve.</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <returns>Returns an instance of the Entity class.</returns>
		public override SecurityFoundation.Entities.ObjectDefinition Get(TransactionManager transactionManager, SecurityFoundation.Entities.ObjectDefinitionKey key, int start, int pageLength)
		{
			return GetByObjectId(transactionManager, key.ObjectId, start, pageLength);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the primary key PK_ObjectDefinition index.
		/// </summary>
		/// <param name="_objectId"></param>
		/// <returns>Returns an instance of the <see cref="SecurityFoundation.Entities.ObjectDefinition"/> class.</returns>
		public SecurityFoundation.Entities.ObjectDefinition GetByObjectId(System.Guid _objectId)
		{
			int count = -1;
			return GetByObjectId(null,_objectId, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_ObjectDefinition index.
		/// </summary>
		/// <param name="_objectId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="SecurityFoundation.Entities.ObjectDefinition"/> class.</returns>
		public SecurityFoundation.Entities.ObjectDefinition GetByObjectId(System.Guid _objectId, int start, int pageLength)
		{
			int count = -1;
			return GetByObjectId(null, _objectId, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_ObjectDefinition index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_objectId"></param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="SecurityFoundation.Entities.ObjectDefinition"/> class.</returns>
		public SecurityFoundation.Entities.ObjectDefinition GetByObjectId(TransactionManager transactionManager, System.Guid _objectId)
		{
			int count = -1;
			return GetByObjectId(transactionManager, _objectId, 0, int.MaxValue, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_ObjectDefinition index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_objectId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="SecurityFoundation.Entities.ObjectDefinition"/> class.</returns>
		public SecurityFoundation.Entities.ObjectDefinition GetByObjectId(TransactionManager transactionManager, System.Guid _objectId, int start, int pageLength)
		{
			int count = -1;
			return GetByObjectId(transactionManager, _objectId, start, pageLength, out count);
		}
		
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_ObjectDefinition index.
		/// </summary>
		/// <param name="_objectId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">out parameter to get total records for query</param>
		/// <remarks></remarks>
		/// <returns>Returns an instance of the <see cref="SecurityFoundation.Entities.ObjectDefinition"/> class.</returns>
		public SecurityFoundation.Entities.ObjectDefinition GetByObjectId(System.Guid _objectId, int start, int pageLength, out int count)
		{
			return GetByObjectId(null, _objectId, start, pageLength, out count);
		}
		
				
		/// <summary>
		/// 	Gets rows from the datasource based on the PK_ObjectDefinition index.
		/// </summary>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="_objectId"></param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="count">The total number of records.</param>
		/// <returns>Returns an instance of the <see cref="SecurityFoundation.Entities.ObjectDefinition"/> class.</returns>
		public abstract SecurityFoundation.Entities.ObjectDefinition GetByObjectId(TransactionManager transactionManager, System.Guid _objectId, int start, int pageLength, out int count);
						
		#endregion "Get By Index Functions"
	
		#region Custom Methods
		
		
		#region usp_ObjectDefinition_GetByCategory 
		
		/// <summary>
		///	This method wrap the 'usp_ObjectDefinition_GetByCategory' stored procedure. 
		/// </summary>
		/// <param name="applicationkey"> A <c>System.Guid?</c> instance.</param>
		/// <param name="category"> A <c>System.String</c> instance.</param>
		/// <remark>This method is generate from a stored procedure.</remark>
		/// <returns>A <see cref="TList&lt;ObjectDefinition&gt;"/> instance.</returns>
		public TList<ObjectDefinition> GetByCategory(System.Guid? applicationkey, System.String category)
		{
			return GetByCategory(null, 0, int.MaxValue , applicationkey, category);
		}
		
		/// <summary>
		///	This method wrap the 'usp_ObjectDefinition_GetByCategory' stored procedure. 
		/// </summary>
		/// <param name="applicationkey"> A <c>System.Guid?</c> instance.</param>
		/// <param name="category"> A <c>System.String</c> instance.</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <remark>This method is generate from a stored procedure.</remark>
		/// <returns>A <see cref="TList&lt;ObjectDefinition&gt;"/> instance.</returns>
		public TList<ObjectDefinition> GetByCategory(int start, int pageLength, System.Guid? applicationkey, System.String category)
		{
			return GetByCategory(null, start, pageLength , applicationkey, category);
		}
				
		/// <summary>
		///	This method wrap the 'usp_ObjectDefinition_GetByCategory' stored procedure. 
		/// </summary>
		/// <param name="applicationkey"> A <c>System.Guid?</c> instance.</param>
		/// <param name="category"> A <c>System.String</c> instance.</param>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <remark>This method is generate from a stored procedure.</remark>
		/// <returns>A <see cref="TList&lt;ObjectDefinition&gt;"/> instance.</returns>
		public TList<ObjectDefinition> GetByCategory(TransactionManager transactionManager, System.Guid? applicationkey, System.String category)
		{
			return GetByCategory(transactionManager, 0, int.MaxValue , applicationkey, category);
		}
		
		/// <summary>
		///	This method wrap the 'usp_ObjectDefinition_GetByCategory' stored procedure. 
		/// </summary>
		/// <param name="applicationkey"> A <c>System.Guid?</c> instance.</param>
		/// <param name="category"> A <c>System.String</c> instance.</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">Number of rows to return.</param>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <remark>This method is generate from a stored procedure.</remark>
		/// <returns>A <see cref="TList&lt;ObjectDefinition&gt;"/> instance.</returns>
		public abstract TList<ObjectDefinition> GetByCategory(TransactionManager transactionManager, int start, int pageLength , System.Guid? applicationkey, System.String category);
		
		#endregion
		
		#endregion

		#region Helper Functions	
		
		/// <summary>
		/// Fill a TList&lt;ObjectDefinition&gt; From a DataReader.
		/// </summary>
		/// <param name="reader">Datareader</param>
		/// <param name="rows">The collection to fill</param>
		/// <param name="start">Row number at which to start reading, the first row is 0.</param>
		/// <param name="pageLength">number of rows.</param>
		/// <returns>a <see cref="TList&lt;ObjectDefinition&gt;"/></returns>
		public static TList<ObjectDefinition> Fill(IDataReader reader, TList<ObjectDefinition> rows, int start, int pageLength)
		{
			NetTiersProvider currentProvider = DataRepository.Provider;
            bool useEntityFactory = currentProvider.UseEntityFactory;
            bool enableEntityTracking = currentProvider.EnableEntityTracking;
            LoadPolicy currentLoadPolicy = currentProvider.CurrentLoadPolicy;
			Type entityCreationFactoryType = currentProvider.EntityCreationalFactoryType;
			
			// advance to the starting row
			for (int i = 0; i < start; i++)
			{
				if (!reader.Read())
				return rows; // not enough rows, just return
			}
			for (int i = 0; i < pageLength; i++)
			{
				if (!reader.Read())
					break; // we are done
					
				string key = null;
				
				SecurityFoundation.Entities.ObjectDefinition c = null;
				if (useEntityFactory)
				{
					key = new System.Text.StringBuilder("ObjectDefinition")
					.Append("|").Append((System.Guid)reader[((int)ObjectDefinitionColumn.ObjectId - 1)]).ToString();
					c = EntityManager.LocateOrCreate<ObjectDefinition>(
					key.ToString(), // EntityTrackingKey
					"ObjectDefinition",  //Creational Type
					entityCreationFactoryType,  //Factory used to create entity
					enableEntityTracking); // Track this entity?
				}
				else
				{
					c = new SecurityFoundation.Entities.ObjectDefinition();
				}
				
				if (!enableEntityTracking ||
					c.EntityState == EntityState.Added ||
					(enableEntityTracking &&
					
						(
							(currentLoadPolicy == LoadPolicy.PreserveChanges && c.EntityState == EntityState.Unchanged) ||
							(currentLoadPolicy == LoadPolicy.DiscardChanges && c.EntityState != EntityState.Unchanged)
						)
					))
				{
					c.SuppressEntityEvents = true;
					c.ObjectId = (System.Guid)reader[((int)ObjectDefinitionColumn.ObjectId - 1)];
					c.OriginalObjectId = c.ObjectId;
					c.ObjectName = (System.String)reader[((int)ObjectDefinitionColumn.ObjectName - 1)];
					c.ApplicationKey = (System.Guid)reader[((int)ObjectDefinitionColumn.ApplicationKey - 1)];
					c.SchemaDefinition = (reader.IsDBNull(((int)ObjectDefinitionColumn.SchemaDefinition - 1)))?null:(System.String)reader[((int)ObjectDefinitionColumn.SchemaDefinition - 1)];
					c.OwnerRole = (System.String)reader[((int)ObjectDefinitionColumn.OwnerRole - 1)];
					c.Added = (System.DateTime)reader[((int)ObjectDefinitionColumn.Added - 1)];
					c.Audited = (System.Boolean)reader[((int)ObjectDefinitionColumn.Audited - 1)];
					c.FieldLevelSecurity = (System.Int32)reader[((int)ObjectDefinitionColumn.FieldLevelSecurity - 1)];
					c.ObjectCategory = (System.String)reader[((int)ObjectDefinitionColumn.ObjectCategory - 1)];
					c.EntityTrackingKey = key;
					c.AcceptChanges();
					c.SuppressEntityEvents = false;
				}
				rows.Add(c);
			}
		return rows;
		}		
		/// <summary>
		/// Refreshes the <see cref="SecurityFoundation.Entities.ObjectDefinition"/> object from the <see cref="IDataReader"/>.
		/// </summary>
		/// <param name="reader">The <see cref="IDataReader"/> to read from.</param>
		/// <param name="entity">The <see cref="SecurityFoundation.Entities.ObjectDefinition"/> object to refresh.</param>
		public static void RefreshEntity(IDataReader reader, SecurityFoundation.Entities.ObjectDefinition entity)
		{
			if (!reader.Read()) return;
			
			entity.ObjectId = (System.Guid)reader[((int)ObjectDefinitionColumn.ObjectId - 1)];
			entity.OriginalObjectId = (System.Guid)reader["ObjectID"];
			entity.ObjectName = (System.String)reader[((int)ObjectDefinitionColumn.ObjectName - 1)];
			entity.ApplicationKey = (System.Guid)reader[((int)ObjectDefinitionColumn.ApplicationKey - 1)];
			entity.SchemaDefinition = (reader.IsDBNull(((int)ObjectDefinitionColumn.SchemaDefinition - 1)))?null:(System.String)reader[((int)ObjectDefinitionColumn.SchemaDefinition - 1)];
			entity.OwnerRole = (System.String)reader[((int)ObjectDefinitionColumn.OwnerRole - 1)];
			entity.Added = (System.DateTime)reader[((int)ObjectDefinitionColumn.Added - 1)];
			entity.Audited = (System.Boolean)reader[((int)ObjectDefinitionColumn.Audited - 1)];
			entity.FieldLevelSecurity = (System.Int32)reader[((int)ObjectDefinitionColumn.FieldLevelSecurity - 1)];
			entity.ObjectCategory = (System.String)reader[((int)ObjectDefinitionColumn.ObjectCategory - 1)];
			entity.AcceptChanges();
		}
		
		/// <summary>
		/// Refreshes the <see cref="SecurityFoundation.Entities.ObjectDefinition"/> object from the <see cref="DataSet"/>.
		/// </summary>
		/// <param name="dataSet">The <see cref="DataSet"/> to read from.</param>
		/// <param name="entity">The <see cref="SecurityFoundation.Entities.ObjectDefinition"/> object.</param>
		public static void RefreshEntity(DataSet dataSet, SecurityFoundation.Entities.ObjectDefinition entity)
		{
			DataRow dataRow = dataSet.Tables[0].Rows[0];
			
			entity.ObjectId = (System.Guid)dataRow["ObjectID"];
			entity.OriginalObjectId = (System.Guid)dataRow["ObjectID"];
			entity.ObjectName = (System.String)dataRow["ObjectName"];
			entity.ApplicationKey = (System.Guid)dataRow["ApplicationKey"];
			entity.SchemaDefinition = Convert.IsDBNull(dataRow["SchemaDefinition"]) ? null : (System.String)dataRow["SchemaDefinition"];
			entity.OwnerRole = (System.String)dataRow["OwnerRole"];
			entity.Added = (System.DateTime)dataRow["Added"];
			entity.Audited = (System.Boolean)dataRow["Audited"];
			entity.FieldLevelSecurity = (System.Int32)dataRow["FieldLevelSecurity"];
			entity.ObjectCategory = (System.String)dataRow["ObjectCategory"];
			entity.AcceptChanges();
		}
		#endregion 
		
		#region DeepLoad Methods
		/// <summary>
		/// Deep Loads the <see cref="IEntity"/> object with criteria based of the child 
		/// property collections only N Levels Deep based on the <see cref="DeepLoadType"/>.
		/// </summary>
		/// <remarks>
		/// Use this method with caution as it is possible to DeepLoad with Recursion and traverse an entire object graph.
		/// </remarks>
		/// <param name="transactionManager"><see cref="TransactionManager"/> object</param>
		/// <param name="entity">The <see cref="SecurityFoundation.Entities.ObjectDefinition"/> object to load.</param>
		/// <param name="deep">Boolean. A flag that indicates whether to recursively save all Property Collection that are descendants of this instance. If True, saves the complete object graph below this object. If False, saves this object only. </param>
		/// <param name="deepLoadType">DeepLoadType Enumeration to Include/Exclude object property collections from Load.</param>
		/// <param name="childTypes">SecurityFoundation.Entities.ObjectDefinition Property Collection Type Array To Include or Exclude from Load</param>
		/// <param name="innerList">A collection of child types for easy access.</param>
	    /// <exception cref="ArgumentNullException">entity or childTypes is null.</exception>
	    /// <exception cref="ArgumentException">deepLoadType has invalid value.</exception>
		public override void DeepLoad(TransactionManager transactionManager, SecurityFoundation.Entities.ObjectDefinition entity, bool deep, DeepLoadType deepLoadType, System.Type[] childTypes, DeepSession innerList)
		{
			if(entity == null)
				return;

			#region ApplicationKeySource	
			if (CanDeepLoad(entity, "ApplicationDefination|ApplicationKeySource", deepLoadType, innerList) 
				&& entity.ApplicationKeySource == null)
			{
				object[] pkItems = new object[1];
				pkItems[0] = entity.ApplicationKey;
				ApplicationDefination tmpEntity = EntityManager.LocateEntity<ApplicationDefination>(EntityLocator.ConstructKeyFromPkItems(typeof(ApplicationDefination), pkItems), DataRepository.Provider.EnableEntityTracking);
				if (tmpEntity != null)
					entity.ApplicationKeySource = tmpEntity;
				else
					entity.ApplicationKeySource = DataRepository.ApplicationDefinationProvider.GetByApplicationKey(transactionManager, entity.ApplicationKey);		
				
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'ApplicationKeySource' loaded. key " + entity.EntityTrackingKey);
				#endif 
				
				if (deep && entity.ApplicationKeySource != null)
				{
					innerList.SkipChildren = true;
					DataRepository.ApplicationDefinationProvider.DeepLoad(transactionManager, entity.ApplicationKeySource, deep, deepLoadType, childTypes, innerList);
					innerList.SkipChildren = false;
				}
					
			}
			#endregion ApplicationKeySource
			
			//used to hold DeepLoad method delegates and fire after all the local children have been loaded.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
			// Deep load child collections  - Call GetByObjectId methods when available
			
			#region FieldDefinitionCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<FieldDefinition>|FieldDefinitionCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'FieldDefinitionCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.FieldDefinitionCollection = DataRepository.FieldDefinitionProvider.GetByObjectId(transactionManager, entity.ObjectId);

				if (deep && entity.FieldDefinitionCollection.Count > 0)
				{
					deepHandles.Add("FieldDefinitionCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<FieldDefinition>) DataRepository.FieldDefinitionProvider.DeepLoad,
						new object[] { transactionManager, entity.FieldDefinitionCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			#region ObjectAclCollection
			//Relationship Type One : Many
			if (CanDeepLoad(entity, "List<ObjectAcl>|ObjectAclCollection", deepLoadType, innerList)) 
			{
				#if NETTIERS_DEBUG
				System.Diagnostics.Debug.WriteLine("- property 'ObjectAclCollection' loaded. key " + entity.EntityTrackingKey);
				#endif 

				entity.ObjectAclCollection = DataRepository.ObjectAclProvider.GetByObjectId(transactionManager, entity.ObjectId);

				if (deep && entity.ObjectAclCollection.Count > 0)
				{
					deepHandles.Add("ObjectAclCollection",
						new KeyValuePair<Delegate, object>((DeepLoadHandle<ObjectAcl>) DataRepository.ObjectAclProvider.DeepLoad,
						new object[] { transactionManager, entity.ObjectAclCollection, deep, deepLoadType, childTypes, innerList }
					));
				}
			}		
			#endregion 
			
			
			//Fire all DeepLoad Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			deepHandles = null;
		}
		
		#endregion 
		
		#region DeepSave Methods

		/// <summary>
		/// Deep Save the entire object graph of the SecurityFoundation.Entities.ObjectDefinition object with criteria based of the child 
		/// Type property array and DeepSaveType.
		/// </summary>
		/// <param name="transactionManager">The transaction manager.</param>
		/// <param name="entity">SecurityFoundation.Entities.ObjectDefinition instance</param>
		/// <param name="deepSaveType">DeepSaveType Enumeration to Include/Exclude object property collections from Save.</param>
		/// <param name="childTypes">SecurityFoundation.Entities.ObjectDefinition Property Collection Type Array To Include or Exclude from Save</param>
		/// <param name="innerList">A Hashtable of child types for easy access.</param>
		public override bool DeepSave(TransactionManager transactionManager, SecurityFoundation.Entities.ObjectDefinition entity, DeepSaveType deepSaveType, System.Type[] childTypes, DeepSession innerList)
		{	
			if (entity == null)
				return false;
							
			#region Composite Parent Properties
			//Save Source Composite Properties, however, don't call deep save on them.  
			//So they only get saved a single level deep.
			
			#region ApplicationKeySource
			if (CanDeepSave(entity, "ApplicationDefination|ApplicationKeySource", deepSaveType, innerList) 
				&& entity.ApplicationKeySource != null)
			{
				DataRepository.ApplicationDefinationProvider.Save(transactionManager, entity.ApplicationKeySource);
				entity.ApplicationKey = entity.ApplicationKeySource.ApplicationKey;
			}
			#endregion 
			#endregion Composite Parent Properties

			// Save Root Entity through Provider
			if (!entity.IsDeleted)
				this.Save(transactionManager, entity);
			
			//used to hold DeepSave method delegates and fire after all the local children have been saved.
			Dictionary<string, KeyValuePair<Delegate, object>> deepHandles = new Dictionary<string, KeyValuePair<Delegate, object>>();
	
			#region List<FieldDefinition>
				if (CanDeepSave(entity.FieldDefinitionCollection, "List<FieldDefinition>|FieldDefinitionCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(FieldDefinition child in entity.FieldDefinitionCollection)
					{
						if(child.ObjectIdSource != null)
						{
							child.ObjectId = child.ObjectIdSource.ObjectId;
						}
						else
						{
							child.ObjectId = entity.ObjectId;
						}

					}

					if (entity.FieldDefinitionCollection.Count > 0 || entity.FieldDefinitionCollection.DeletedItems.Count > 0)
					{
						//DataRepository.FieldDefinitionProvider.Save(transactionManager, entity.FieldDefinitionCollection);
						
						deepHandles.Add("FieldDefinitionCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< FieldDefinition >) DataRepository.FieldDefinitionProvider.DeepSave,
							new object[] { transactionManager, entity.FieldDefinitionCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
	
			#region List<ObjectAcl>
				if (CanDeepSave(entity.ObjectAclCollection, "List<ObjectAcl>|ObjectAclCollection", deepSaveType, innerList)) 
				{	
					// update each child parent id with the real parent id (mostly used on insert)
					foreach(ObjectAcl child in entity.ObjectAclCollection)
					{
						if(child.ObjectIdSource != null)
						{
							child.ObjectId = child.ObjectIdSource.ObjectId;
						}
						else
						{
							child.ObjectId = entity.ObjectId;
						}

					}

					if (entity.ObjectAclCollection.Count > 0 || entity.ObjectAclCollection.DeletedItems.Count > 0)
					{
						//DataRepository.ObjectAclProvider.Save(transactionManager, entity.ObjectAclCollection);
						
						deepHandles.Add("ObjectAclCollection",
						new KeyValuePair<Delegate, object>((DeepSaveHandle< ObjectAcl >) DataRepository.ObjectAclProvider.DeepSave,
							new object[] { transactionManager, entity.ObjectAclCollection, deepSaveType, childTypes, innerList }
						));
					}
				} 
			#endregion 
				
			//Fire all DeepSave Items
			foreach(KeyValuePair<Delegate, object> pair in deepHandles.Values)
		    {
                pair.Key.DynamicInvoke((object[])pair.Value);
		    }
			
			// Save Root Entity through Provider, if not already saved in delete mode
			if (entity.IsDeleted)
				this.Save(transactionManager, entity);
				

			deepHandles = null;
						
			return true;
		}
		#endregion
	} // end class
	
	#region ObjectDefinitionChildEntityTypes
	
	///<summary>
	/// Enumeration used to expose the different child entity types 
	/// for child properties in <c>SecurityFoundation.Entities.ObjectDefinition</c>
	///</summary>
	public enum ObjectDefinitionChildEntityTypes
	{
		
		///<summary>
		/// Composite Property for <c>ApplicationDefination</c> at ApplicationKeySource
		///</summary>
		[ChildEntityType(typeof(ApplicationDefination))]
		ApplicationDefination,
	
		///<summary>
		/// Collection of <c>ObjectDefinition</c> as OneToMany for FieldDefinitionCollection
		///</summary>
		[ChildEntityType(typeof(TList<FieldDefinition>))]
		FieldDefinitionCollection,

		///<summary>
		/// Collection of <c>ObjectDefinition</c> as OneToMany for ObjectAclCollection
		///</summary>
		[ChildEntityType(typeof(TList<ObjectAcl>))]
		ObjectAclCollection,
	}
	
	#endregion ObjectDefinitionChildEntityTypes
	
	#region ObjectDefinitionFilterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="SqlFilterBuilder&lt;ObjectDefinitionColumn&gt;"/> class
	/// that is used exclusively with a <see cref="ObjectDefinition"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class ObjectDefinitionFilterBuilder : SqlFilterBuilder<ObjectDefinitionColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the ObjectDefinitionFilterBuilder class.
		/// </summary>
		public ObjectDefinitionFilterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the ObjectDefinitionFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public ObjectDefinitionFilterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the ObjectDefinitionFilterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public ObjectDefinitionFilterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion ObjectDefinitionFilterBuilder
	
	#region ObjectDefinitionParameterBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="ParameterizedSqlFilterBuilder&lt;ObjectDefinitionColumn&gt;"/> class
	/// that is used exclusively with a <see cref="ObjectDefinition"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class ObjectDefinitionParameterBuilder : ParameterizedSqlFilterBuilder<ObjectDefinitionColumn>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the ObjectDefinitionParameterBuilder class.
		/// </summary>
		public ObjectDefinitionParameterBuilder() : base() { }

		/// <summary>
		/// Initializes a new instance of the ObjectDefinitionParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		public ObjectDefinitionParameterBuilder(bool ignoreCase) : base(ignoreCase) { }

		/// <summary>
		/// Initializes a new instance of the ObjectDefinitionParameterBuilder class.
		/// </summary>
		/// <param name="ignoreCase">Specifies whether to create case-insensitive statements.</param>
		/// <param name="useAnd">Specifies whether to combine statements using AND or OR.</param>
		public ObjectDefinitionParameterBuilder(bool ignoreCase, bool useAnd) : base(ignoreCase, useAnd) { }

		#endregion Constructors
	}

	#endregion ObjectDefinitionParameterBuilder
	
	#region ObjectDefinitionSortBuilder
    
    /// <summary>
    /// A strongly-typed instance of the <see cref="SqlSortBuilder&lt;ObjectDefinitionColumn&gt;"/> class
	/// that is used exclusively with a <see cref="ObjectDefinition"/> object.
    /// </summary>
    [CLSCompliant(true)]
    public class ObjectDefinitionSortBuilder : SqlSortBuilder<ObjectDefinitionColumn>
    {
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the ObjectDefinitionSqlSortBuilder class.
		/// </summary>
		public ObjectDefinitionSortBuilder() : base() { }

		#endregion Constructors

    }    
    #endregion ObjectDefinitionSortBuilder
	
} // end namespace
